﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using sceye.Properties;

namespace sceye
{
    public partial class Form2 : DevExpress.XtraEditors.XtraForm
    {
        public Form2()
        {
            InitializeComponent();
        }


        void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            camControl1.StopLive();
            camControl1.ExitControl();
        }

        MyData ds = new MyData();
        private void Form2_Load(object sender, EventArgs e)
        {
            string username = "oaykut", password = "Lic059-59469";

            //camControl1.PerformReset();
            camControl1.InitCameraExt(username, password);

            camControl1.StartLive();            //start live picture  
            camControl1.SetAnimation(1, 1);     //disable
            camControl1.SetColorMode(1);        //color mode
            camControl1.SetBrightness(65536);   //auto-brightness
            camControl1.SetAutoDetection(0);    //autodetection on
            camControl1.SetContrast(20);        //contrast 30 (0-100)
            camControl1.LaserSwitch(1);         //laser on
            camControl1.LEDSwitch(0);           //led light on

            btnTake.Click += new EventHandler(btnTake_Click);
            //camControl1.MouseUp += new MouseEventHandler(camControl1_MouseUp);
            //camControl1.MouseDown += new MouseEventHandler(camControl1_MouseDown);
            //camControl1.NotifyImageReadyOnMemory += new sceye_menucam2.CamControl.NotifyImageReadyOnMemoryEventHandler(camControl1_NotifyImageReadyOnMemory);
            //camControl1.NotifyImageReady += new sceye_menucam2.CamControl.NotifyImageReadyEventHandler(camControl1_NotifyImageReady);

            this.FormClosing += new FormClosingEventHandler(Form2_FormClosing);

            gridControl1.DataSource = Retrieve("GetAksesuarFull");

            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.RowSelect;
            gridView1.OptionsBehavior.Editable = false;
            gridView1.BestFitMaxRowCount = 200;
            gridView1.GridControl.ShowOnlyPredefinedDetails = true;
            gridView1.HorzScrollStep = 50;
            gridView1.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
            gridView1.OptionsMenu.EnableColumnMenu = true;
            gridView1.OptionsNavigation.UseOfficePageNavigation = true;
            gridView1.OptionsView.ColumnAutoWidth = false;
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.ShowAutoFilterRow = true;
            gridView1.OptionsView.ShowDetailButtons = false;
            gridView1.OptionsView.ShowGroupPanel = false;
            gridView1.ViewCaption = "Aksesuarlar";
            AddSummary(gridView1);

            gridView1.BestFitColumns();

            button1.Click += new EventHandler(button1_Click);
        }

        void button1_Click(object sender, EventArgs e)
        {
            int AksesuarId = intParse(gridView1.GetFocusedRowCellValue("AksesuarId"));
            DataTable dt = Retrieve("silAks", AksesuarId);
            using (XtraForm f = new XtraForm())
            {
                PictureEdit pe = new PictureEdit();
                pe.Dock = DockStyle.Fill;
                pe.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Clip;
                pe.EditValue = dt.Rows[0]["Photo"];
                f.Controls.Add(pe);
                f.WindowState = FormWindowState.Maximized;
                f.ShowDialog();
            }            
        }



        /*
        void camControl1_NotifyImageReady(string filename)
        {
            throw new NotImplementedException();
        }

        void camControl1_NotifyImageReadyOnMemory(ref int pImg, int width, int height, int bitperpixel, ref bool handled)
        {
            handled = true;

        }

        Point f = new Point();
        void camControl1_MouseDown(object sender, MouseEventArgs e)
        {
            f.X = e.X;
            f.Y = e.Y;
        }

        void camControl1_MouseUp(object sender, MouseEventArgs e)
        {
            camControl1.SetSelection(
                (short)f.X, (short)e.X,
                (short)f.Y, (short)e.Y);
        }

        ~Form2()
        {
        }
        */

        void btnTake_Click(object sender, EventArgs e)
        {
            Scan();
        }

        public int intParse(object i)
        {
            int tmp = 0;
            if (i != null)
                int.TryParse(i.ToString(), out tmp);
            return tmp;
        }

        public byte[] ConvertImageToByteArray(Image imageToConvert)
        {
            byte[] Ret;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, ImageFormat.Jpeg);
                    Ret = ms.ToArray();
                }
            }
            catch (Exception) { return null; }
            return Ret;
        }

        void Scan()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnTake.Enabled = false;

                camControl1.SetSaveColorMode(1);
                camControl1.SetSaveDPI(300);
                camControl1.SetSaveAddParam(9);
                camControl1.GetLastFrameExt("test.jpg", 1);     //(0 = asynchronously, 1 = synchronously)
                //https://www.lires.de/dev_board/viewtopic.php?t=381&p=975
                //http://www.sceye.eu/en/sceye-lounge-sdk/147-sdk-forum/ocx-interface/snapshot-functions
                //http://www.sceye.eu/en/sceye-lounge-sdk/149-sdk-forum/ocx-interface/events

                //byte[] bytes =  File.ReadAllBytes("d:\\test.jpg");
                //i0 = i2 = Image.FromFile("d:\\test.png");
                //i2.Save(@"C:\Shared\" +  intParse(bsAksesuar, "AksesuarId").ToString() + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss")+ ".png");

                using (Image i2 = Image.FromFile("test.jpg"))
                {
                    if (i2 != null)
                    {
                        int AksesuarId = intParse(gridView1.GetFocusedRowCellValue("AksesuarId"));
                        if (ds.xPhotoAks.FindByAksesuarId(AksesuarId) == null)
                        {
                            MyData.xPhotoAksRow xpr = ds.xPhotoAks.NewxPhotoAksRow();
                            xpr.AksesuarId = AksesuarId;
                            ds.xPhotoAks.AddxPhotoAksRow(xpr);
                        }
                        ds.xPhotoAks.FindByAksesuarId(AksesuarId).Photo = ConvertImageToByteArray(i2);

                        ExecQueryTV("UpdPhotoAks", ds.xPhotoAks);
                        gridView1.SetFocusedRowCellValue("Resim", "VAR");
                        ds.xPhotoAks.Clear();
                        GC.Collect();
                    }
                }
                File.Delete("test.jpg");
            }
            finally
            {
                this.Cursor = Cursors.Default;
                btnTake.Enabled = true;
            }

        }
        int ix = 0;

        public void AddSummary(GridView gridView, params string[] columnNames)
        {
            gridView.OptionsView.ShowFooter = true;
            foreach (GridColumn col in gridView.Columns)
                if (col.Visible == true)
                {
                    col.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
                    col.SummaryItem.DisplayFormat = "{0:#,##0} records";
                    break;
                }
        }

        void ExecQueryTV(string SP, params object[] p)
        {
            using (SqlConnection sqlConn = new SqlConnection(Settings.Default.ConfExpertConnectionString))
            {
                sqlConn.Open();
                SqlCommand sqlCmd = sqlConn.CreateCommand();
                sqlCmd.CommandText = SP;
                sqlCmd.CommandType = CommandType.StoredProcedure;
                SqlParameter[] parameters = new SqlParameter[1];
                parameters[0] = new SqlParameter("@tbl", SqlDbType.Structured);
                parameters[0].Value = p[0];
                sqlCmd.Parameters.AddRange(parameters);
                sqlCmd.ExecuteNonQuery();
            }
        }


        DataTable Retrieve(string SP, params object[] p)
        {
            DataTable dt = new DataTable();
            using (SqlConnection sqlConn = new SqlConnection(Settings.Default.ConfExpertConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SP, sqlConn))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        if (p.Length > 0)
                            cmd.Parameters.AddWithValue("AksesuarId", (int)p[0]);

                        //cmd.Parameters.Add(new SqlParameter("@EMPLOYEENO", employeeNo));
                        cmd.CommandType = CommandType.StoredProcedure;
                        da.SelectCommand = cmd;
                        da.Fill(dt);
                    }
                }
            }
            return dt;
        }


    }
}